<template>
  <div class="chart-box" ref="chartBox"></div>
</template>

<script>
import resize from '../mixins/resize'

export default {
  name: "EchartPie",
  mixins: [resize],
  props: {
    data: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      chart: null,
    }
  },
  watch: {
    data: {
      deep: true,
      handler: function (val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = this.$echarts.init(this.$refs.chartBox)
      this.setOptions(this.data)
    },
    setOptions({times = [], data = []}) {
      if (!this.chart) {
        return false
      }
      this.chart.setOption({
        legend: {
          right: 20,
          top: 'center',
          orient: 'vertical',
          textStyle: {
            color: '#ffffff'
          }
        },
        grid: {
          left: 10,
          right: 30,
          bottom: 10,
          top: 10,
          containLabel: true
        },
        tooltip: {
          formatter: '{b}:{c}({d}%)',
          backgroundColor: "rgba(0,0,0,0.8)", //设置背景图片 rgba格式
          color: "white",
          borderWidth: "1", //边框宽度设置1
          borderColor: "gray", //设置边框颜色
          textStyle: {
            fontSize: 14,
            color: "#FFFFFF", //设置文字颜色
          },
        },
        series: {
          name: '',
          type: 'pie',
          radius: ['50%', '60%'],
          center: ['40%', '50%'],
          roseType: 'area',
          label: {
            show: false
          },
          itemStyle: {
            normal: {
              borderRadius: 0,
              color: function (params) {
                const colors = ['#115091', '#1097fe', '#5870da', '#20c6fb']
                if (params.dataIndex < colors.length) {
                  return colors[params.dataIndex]
                } else {
                  return '#27CDE6'
                }
              }
            }
          },
          data: data
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
  .chart-box {
    width: 100%;
    height: 100%;
  }
</style>